package com.twu.biblioteca.domain;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class Repository<T extends LibraryItem> {

    private Map<String, T> idToItem = new HashMap<String, T>();
    private Map<String, Boolean> idToAvailability = new HashMap<String, Boolean>();

    private String getKey(T item) {
        return item.getId();
    }

    public void add(T item) {
        idToItem.put(getKey(item), item);
        idToAvailability.put(getKey(item), true);
    }

    public boolean reserve(String id) throws ItemNotFoundException {
        return reserve(getById(id));
    }

    private boolean reserve(T item) throws ItemNotFoundException {
        ensureNotNull(item);
        ensureFound(item);

        if (!idToAvailability.get(getKey(item))) {
            return false;
        } else {
            idToAvailability.put(getKey(item), false);
            return true;
        }
    }

    private void ensureFound(T item) throws ItemNotFoundException {
        if (idToAvailability.get(getKey(item)) == null) {
            throw new ItemNotFoundException(item.getType(), item.getName());
        }
    }

    private void ensureNotNull(T item) throws ItemNotFoundException {
        if (item == null) {
            throw new ItemNotFoundException();
        }
    }

    public Collection<T> getAll() {
        return idToItem.values();
    }

    public T getById(String id) {
        return idToItem.get(id);
    }
}
